package handler

import (
	"context"

	"user/domain/model"
	"user/domain/service"

	user "user/proto/user"
)

type User struct {
	UserDataService service.IUserDataService
}

// 注册 实现 user/proto中 user.pb.micro 的 UserService方法
func (u *User) Register(ctx context.Context, in *user.UserRegisterRequest, out *user.UserRegisterResponse) error {
	userRegister := &model.User{
		UserName:     in.UserName,
		FirstName:    in.FirstName,
		HashPassword: in.Pwd,
	}
	_, err := u.UserDataService.AddUser(userRegister)
	if err != nil {
		return err
	}
	out.Message = "添加成功"
	return nil
}

// 登录方法
func (u *User) Login(ctx context.Context, in *user.UserLoginRequest, out *user.UserLoginResponse) error {
	isok, err := u.UserDataService.CheckPwd(in.UserName, in.Pwd)
	if err != nil {
		return nil
	}
	out.IsSuccess = isok
	return nil
}

// 获取用户信息
func (u *User) GetUserInfo(ctx context.Context, in *user.UserInfoRequest, out *user.UserInfoResponse) error {
	userInfo, err := u.UserDataService.FindUserByname(in.UserName)
	if err != nil {
		return err
	}
	out = userForResponse(userInfo)
	return nil
}

// 类型转化
func userForResponse(usermodel *model.User) *user.UserInfoResponse {
	return &user.UserInfoResponse{
		UserName:  usermodel.UserName,
		FirstName: usermodel.FirstName,
		UserId:    usermodel.ID,
	}
}
